package Classing;

import java.util.Arrays;

public class Sort {
    //直接插入排序
    public static void insertSort(int[] arrary) {
        for (int i = 1; i < arrary.length; i++) {
            int tmp = arrary[i];
            int j = i - 1;
            for (; j >= 0; j--) {
                if(arrary[j] > tmp) {
                    arrary[j+1] = arrary[j];
                } else {
                    break;
                }
            }
            arrary[j+1] = tmp;
        }
    }
    //希尔排序
    public static void shellSort(int[] arrary) {
        int gap = arrary.length;
        while(gap > 1) {
            gap /= 2;
            shell(arrary,gap);
        }
    }
    public static void shell(int[] arrary,int gap) {
        for (int i = gap; i < arrary.length; i++) {
            int tmp = arrary[i];
            int j = i - gap;
            for (; j >= 0 ; j-=gap) {
                if(arrary[j] > tmp) {
                    arrary[j+gap] = arrary[j];
                } else {
                    break;
                }
            }
            arrary[j+gap] = tmp;
        }
    }
    //选择
    public static void selectSort(int[] array) {
        for (int i = 0; i < array.length; i++) {
            int minIndex = i;
            for (int j = i + 1; j < array.length; j++) {
                if(array[j] < array[minIndex]) {
                    minIndex = j;
                }
            }
            int tmp = array[i];
            array[i] = array[minIndex];
            array[minIndex] = tmp;
        }
    }
    public static void selectSort2(int[] arrary) {
        int left = 0;
        int right = arrary.length - 1;
        while(left < right) {
            int minIndex = left;
            int maxIndex = left;
            for (int i = left + 1; i <= right; i++) {
                if(arrary[i] < arrary[minIndex]) {
                    minIndex = i;
                }
                if(arrary[i] > arrary[maxIndex]) {
                    maxIndex = i;
                }
            }
            swap(arrary,left,minIndex);
            if(left == maxIndex) {
                maxIndex = minIndex;
            }
            swap(arrary,right,maxIndex);
            left++;
            right--;
        }
    }
    public static void swap(int[] arrary,int x,int y) {
        int tmp = arrary[x];
        arrary[x] = arrary[y];
        arrary[y] = tmp;
    }
    public static void main(String[] args) {
        int[] arrary = {2,56,1,5,42,8,4,12,6,3};
        //insertSort(arrary);
        //selectSort(arrary);
        shellSort(arrary);
        //selectSort2(arrary);
        System.out.println(Arrays.toString(arrary));
    }
}
